<template>
  <el-dialog title="" v-model="dialogVisible" width="400px">
    <div class="log-manager">
      <div class="log-header">
        <span class="log-title">日志管理</span>
        <span class="log-count">({{ logStats.total }})</span>
      </div>

      <div class="log-controls">
        <el-button type="primary" size="small" @click="exportJSON"> 导出JSON </el-button>
        <el-button type="success" size="small" @click="exportText"> 导出TXT </el-button>
        <el-button type="warning" size="small" @click="clearLogs"> 清空 </el-button>
      </div>

      <div class="log-stats" v-if="logStats.total > 0">
        <el-tag size="small" v-if="logStats.byLevel.error" type="danger">
          错误: {{ logStats.byLevel.error }}
        </el-tag>
        <el-tag size="small" v-if="logStats.byLevel.warn" type="warning">
          警告: {{ logStats.byLevel.warn }}
        </el-tag>
        <el-tag size="small" v-if="logStats.byLevel.info" type="info">
          信息: {{ logStats.byLevel.info }}
        </el-tag>
      </div>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import logger from '@/utils/logger'

const logStats = computed(() => logger.getLogStats())

const dialogVisible = ref(false)

const open = () => {
  dialogVisible.value = true
}
defineExpose({ open })

const exportJSON = () => {
  try {
    logger.exportLogs()
    ElMessage.success('日志已导出为JSON格式')
  } catch (e: any) {
    ElMessage.error('导出失败: ' + e.message)
  }
}

const exportText = () => {
  try {
    logger.exportLogsAsText()
    ElMessage.success('日志已导出为文本格式')
  } catch (e: any) {
    ElMessage.error('导出失败: ' + e.message)
  }
}

const clearLogs = async () => {
  try {
    await ElMessageBox.confirm('确定要清空所有日志吗？此操作不可恢复。', '确认清空', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    logger.clearLogs()
    ElMessage.success('日志已清空')
  } catch {
    // 用户取消
  }
}
</script>

<style scoped>
.log-manager {
  min-width: 200px;
}

.log-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  font-size: 14px;
  font-weight: 500;
  color: #172b4d;
}

.log-title {
  color: #0052cc;
}

.log-count {
  color: #666;
  margin-left: 4px;
}

.log-controls {
  display: flex;
  flex-direction: column;
  gap: 6px;
  margin-bottom: 10px;
}

.log-controls .el-button {
  width: 100%;
  justify-content: flex-start;
}

.log-stats {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.log-stats .el-tag {
  width: 100%;
  justify-content: center;
}
</style>
